package ribbon.controller;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
import ribbon.entity.UserEntity;

import java.net.URI;

/**
 * Created by Administrator on 2016/11/2.
 */
@RestController
public class RibbonController {
    private Logger logger = Logger.getLogger(this.getClass());
    @Autowired
    @Qualifier("LBrestTemplate")
    private RestTemplate restTemplate;

    @Autowired
    private LoadBalancerClient loadBalancer;

    @RequestMapping(value = "/ribbonuser/{id}",method = RequestMethod.GET)
    public String getUserById(@PathVariable("id") String id) {
        String url = "http://sampleServiceA/user/" + id;
        logger.info(url);
        UserEntity userEntity = restTemplate.getForEntity(url, UserEntity.class).getBody();
        return userEntity.getName();
    }

    private String name="wwww";

    @RequestMapping(value = "/name", method = RequestMethod.GET)
    public String getName() {
        return name;
    }

    public URI getRestUrl(String serviceId, String fallbackUri) {
        URI uri = null;
        try {
            ServiceInstance instance = loadBalancer.choose(serviceId);
            uri = instance.getUri();

        } catch (RuntimeException e) {
            uri = URI.create(fallbackUri);
        }

        return uri;
    }
}
